import axios from 'axios'
import pako from 'pako'
//真是的企业级项目中，会根据当前的环境进行一个配置
const baseUrl = 'https://liu.myfristweb.com'

class HttpRequest {
	constructor(baseUrl) {
		this.baseUrl = baseUrl
	}
	
	ungzipString(base64) {
		const binaryString = atob(base64);
		const uint8Array = new Uint8Array(binaryString.length);
		for (let i = 0; i < binaryString.length; i++) {
			uint8Array[i] = binaryString.charCodeAt(i);
		}
		const decompressed = pako.ungzip(uint8Array);
		return new TextDecoder().decode(decompressed);
	}
	getInsideConfig() {
		const config = {
			baseUrl: this.baseUrl,
			header: {}
		}
		return config
	}
	
	interceptors(instance) {
		// 添加请求拦截器
		instance.interceptors.request.use(function (config) {
		    // 在发送请求之前做些什么
		    return config;
		  }, function (error) {
		    // 对请求错误做些什么
		    return Promise.reject(error);
		  });
		
		// 添加响应拦截器
		instance.interceptors.response.use(function (response) {
		    // 对响应数据做点什么
			const {data,code} = response.data
			console.log(response.data);
			if(code == 200) {
				let base64 = data;
				const binaryString = atob(base64);
				const uint8Array = new Uint8Array(binaryString.length);
				for (let i = 0; i < binaryString.length; i++) {
					uint8Array[i] = binaryString.charCodeAt(i);
				}
				const decompressed = pako.ungzip(uint8Array);
				let result = new TextDecoder().decode(decompressed);
				console.log(result);
				return JSON.parse(result);
			}else {
				
			}
		    // return response;
		  }, function (error) {
		    // 对响应错误做点什么
		    return Promise.reject(error);
		  });
	}
	
	request(options) {
		const instance = axios.create()
		options = {...this.getInsideConfig(),...options}
		this.interceptors(instance)
		return instance(options)
	}
	
}

export default new HttpRequest(baseUrl)